/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shared;

/**
 *
 * @author eros
 */



import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;

public class InitLog4j extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	private static final String logPath = "/WEB-INF/logs/tminterface_errors.log";

	public InitLog4j() {
		super();
	}


	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
    @Override
	public void init() throws ServletException {
		FileAppender appender = getAppender(logPath);
		if(appender == null) return ;
		initLogger(null, appender, Level.ERROR);
		initLogger("org.apache.commons.beanutils", appender, Level.DEBUG);
	}
	private FileAppender getAppender(String fileName) {
		RollingFileAppender appender = null;
		try {
			appender = new RollingFileAppender(new PatternLayout("%-5p %c %t%n%29d - %m%n"),getServletContext().getRealPath(fileName));
		}catch(IOException xcp) {
			System.out.println("Could not create an appender for "+fileName+" : "+xcp.getMessage());
		}

		return appender;
	}

	private void initLogger(String name,FileAppender appender,Level level) {
		Logger logger;
		if(name == null) {
			logger = Logger.getRootLogger();
		}else {
			logger = Logger.getLogger(name);
		}

		logger.setLevel(level);
		logger.addAppender(appender);
		logger.info("Starting "+logger.getName());
	}

}
